/**
 * Created by 张强 on 2017/6/2.
 */
import appUserHelper from './userHelper';
import jsApi from './cx580.jsApi';
import urlOperation from './urlOperation';
class Login {
    constructor() {
        this.channel = urlOperation.getParameters().detailUserType;
    }

    //根据不同渠道获取单点登录参数
    _getTypeByChannel() {
        var type = {};
        switch (this.channel) {
            case undefined:
                type = {
                    authType: 'AliPayCityService',
                    userType: 'AliPay'
                };
                break;
            case 'alipay':
                type = {
                    authType: 'AliPay',
                    userType: 'AliPay'
                };
                break;
            case 'weixin':
                type = {
                    authType: 'weixin',
                    userType: 'weixin'
                };
                break;
            case 'qq_city':
                type = {
                    authType: 'QQCityService',
                    userType: 'QQ'
                };
                break;
            case 'qq':
                type = {
                    authType: 'QQ',
                    userType: 'QQ'
                };
                break;
        }
        return type;
    }

    //单点登录
    _singleSignOn() {
        var search = '?' + window.location.href.split('?')[1];
        //判断是否为首页
        var pattern = /\S+index.html[^(\/)]*([#|%23])?(\/)?$/;
        var isHome = pattern.test(window.location.href);
        //判断是否已经登录过，路由内部判断
        var isLogined = sessionStorage.getItem('loginStatus') == 'true';
        if (isHome && !isLogined && !urlOperation.getParameters().userId) {
            //首页检测不到登录信息，跳单点登录
            //清除所有前端缓存
            localStorage.removeItem("userId");
            localStorage.removeItem("token");
            localStorage.removeItem("userType");
            localStorage.removeItem("openId");
                if (window.location.host.indexOf("localhost") !== -1) {
                    //本地PC调试
                } else {
                    // alert('单点登录2');
                    var loginType = this._getTypeByChannel();
                    var homeUrl = window.location.href;
                    var authIstest = window.location.host === 'webservice.cx580.com' ? 'https://jumpUrl.cx580.com/' : 'http://testauth.cx580.com/'; //正式||测试 单点登录
                    //单点登录返回地址仅能带一个参数，单点登录之前缓存详细渠道信息，防止登录之后参数丢失
                   // localStorage.setItem('detailUserType', this.channel ? this.channel : 'alipay_city');
                   // alert(`${authIstest}Auth.aspx?authType=${loginType.authType}&userType=${loginType.userType}&clientId=CheWu&redirect_uri=${homeUrl}`);
                    window.location.replace(`${authIstest}Auth.aspx?authType=${loginType.authType}&userType=${loginType.userType}&clientId=CheWu&redirect_uri=${homeUrl}`);
                }
            return false;
        }
        else if (localStorage.getItem("userId") != null) {
            //非首页，已登录过
            /*alert('1'+localStorage.getItem("userId"));*/
            //如果本地缓存中存在用户信息则直接复制到session中供代码调用
            sessionStorage.setItem("userId", localStorage.getItem("userId"));
            sessionStorage.setItem("token", localStorage.getItem("token"));
            sessionStorage.setItem("userType", localStorage.getItem("userType"));
            sessionStorage.setItem("openId", localStorage.getItem("openId"));
            return true;
        }
        else if(urlOperation.getParameters().userId){
            //首页登录之后回到页面，执行初始化信息操作
            /*    alert('2'+localStorage.getItem("userId"));*/
            var userId = '';
            userId = /[\?|&]userId=([^&]+)/g;
            userId = userId.exec(search);
            userId = userId ? userId[1] : "";
            sessionStorage.setItem("userId", userId); //保存openId
            var token = '';
            token = /[\?|&]token=([^&]+)/g;
            token = token.exec(search);
            token = token ? token[1] : "";
            sessionStorage.setItem("token", token); //保存token
            var userType = '';
            userType = /[\?|&]userType=([^&]+)/g;
            userType = userType.exec(search);
            userType = userType ? userType[1] : "";
            sessionStorage.setItem("userType", userType); //保存userType
            var openId = '';
            openId = /[\?|&]userOpenId=([^&]+)/g;
            openId = openId.exec(search);
            openId = openId ? openId[1] : "";
            sessionStorage.setItem("openId", openId); //保存userType
            //用户信息缓存本地
            localStorage.setItem("userId", userId);
            localStorage.setItem("token", token);
            localStorage.setItem("userType", userType);
            localStorage.setItem("openId", openId);
            sessionStorage.setItem("loginStatus", "true");


            //return this._redirectToDetail();
            return true;
        }
        else if(!isHome){
            //非首页页面，直接返回渲染
            return true;
        }
    }


    //产品详情页无登录状态进入，会带orderid跳转到首页进行登录，此处为登录后带orderid跳转回产品详情页
    _redirectToDetail() {
        let parameters = urlOperation.getParameters();
        let orderId = parameters.orderId;
        localStorage.setItem('orderDetailLoginStatus','true');
        //缓存渠道信息供之后页面调用
        /*alert(location.href);
         alert(orderId);*/
        if (orderId) {
            var href = window.location.href.split('?')[0].replace('#/', '');
            window.location.replace(`${href}#/orderDetails/?OutTradeNo=${orderId}`);
            return false;
        }

        return true;
    }

    //app登录
    _appLogin(callBack) {
        setTimeout(() => {
            appUserHelper.getUserIdAndTokenWithCallBack(() => {
                if (!sessionStorage.getItem("userId")) {
                    appUserHelper.Login(callBack, () => {
                        // jsApi.call(
                        //     {
                        //         "commandId": "",
                        //         "command": "close"
                        //     });
                    });
                }
                else {
                    callBack();
                }
            })
        }, 300);
    }

    //app登录（对外方法）
    appLogin(callBack) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            this._appLogin(callBack);
        }
        else {
            callBack();
        }
    }

    loginOperation(callBack) {
        if (this.channel != 'app') {
            this._singleSignOn() && callBack();
        }
        if(callBack){
            callBack();
        }
        // else {
        //     this._appLogin(callBack);
        // }
    }

    isAppOperation(callBack){
	    if (this.channel == 'app') {
		    this._appLogin(callBack);
		    return false;
      } else {
		    callBack&&callBack();
      }

    }
}

export default  new Login();